package config

import (
	"fmt"
	"os"
	"time"

	"gopkg.in/yaml.v3"
)

type ResourcesConfig struct {
	SexPath string `yaml:"sex_path"`
}

type Config struct {
	Server    ServerConfig    `yaml:"server"`
	Redis     RedisConfig     `yaml:"redis"`
	Scanner   ScannerConfig   `yaml:"scanner"`
	Scheduler SchedulerConfig `yaml:"scheduler"`
	Log       LogConfig       `yaml:"log"`
	Video     VideoConfig     `yaml:"video"`
	Image     ImageConfig     `yaml:"image"`
	Resources ResourcesConfig `yaml:"resources"`
}

type ImageConfig struct {
	RootPath       string   `yaml:"root_path"`
	FileExtensions []string `yaml:"file_extensions"`
	MaxFiles       int      `yaml:"max_files"`
	Workers        int      `yaml:"workers"`
	SelectCount    int      `yaml:"select_count"`
	RedisKey       string   `yaml:"redis_key"`
	BaseURL        string   `yaml:"base_url"`
}

type ServerConfig struct {
	Port int    `yaml:"port"`
	Mode string `yaml:"mode"`
}

type RedisConfig struct {
	Host       string `yaml:"host"`
	Port       int    `yaml:"port"`
	Password   string `yaml:"password"`
	DB         int    `yaml:"db"`
	MaxRetries int    `yaml:"max_retries"`
	PoolSize   int    `yaml:"pool_size"`
}

type ScannerConfig struct {
	RootPaths      []string `yaml:"root_paths"`
	MaxFiles       int      `yaml:"max_files"`
	FileExtensions []string `yaml:"file_extensions"`
	Workers        int      `yaml:"workers"`
	SelectCount    int      `yaml:"select_count"`
}

type SchedulerConfig struct {
	Interval     string `yaml:"interval"`
	Timeout      string `yaml:"timeout"`
	ImmediateRun bool   `yaml:"immediate_run"`
}

type LogConfig struct {
	Level      string `yaml:"level"`
	Output     string `yaml:"output"`
	MaxSize    int    `yaml:"max_size"`
	MaxBackups int    `yaml:"max_backups"`
	MaxAge     int    `yaml:"max_age"`
}

type VideoConfig struct {
	BaseURL  string        `yaml:"base_url"`
	RedisKey string        `yaml:"redis_key"`
	CacheTTL time.Duration `yaml:"cache_ttl"`
}

func LoadConfig(path string) (*Config, error) {
	data, err := os.ReadFile(path)
	if err != nil {
		return nil, fmt.Errorf("读取配置文件失败: %w", err)
	}

	var config Config
	if err := yaml.Unmarshal(data, &config); err != nil {
		return nil, fmt.Errorf("解析配置文件失败: %w", err)
	}

	// 设置默认值
	if config.Scanner.Workers <= 0 {
		config.Scanner.Workers = 3
	}
	if config.Scanner.SelectCount <= 0 {
		config.Scanner.SelectCount = 10
	}
	if config.Scheduler.Interval == "" {
		config.Scheduler.Interval = "6h"
	}

	return &config, nil
}

func (c *Config) GetRedisAddr() string {
	return fmt.Sprintf("%s:%d", c.Redis.Host, c.Redis.Port)
}

func (c *Config) GetIntervalDuration() (time.Duration, error) {
	return time.ParseDuration(c.Scheduler.Interval)
}

func (c *Config) GetTimeoutDuration() (time.Duration, error) {
	return time.ParseDuration(c.Scheduler.Timeout)
}
